/**
 * goio-bean
 * 
 * This class do
 * 
 * @link http://www.marcosperon.com/
 * @copyright 2009 - Peron Co.
 * @author Marcos Peron
 * @package com.marcosperon.dao.creator
 * @version 2009
 */
package com.mperon.dao.creator;

import com.mperon.dao.DAO;
import com.mperon.dao.DAOException;
import com.mperon.util.config.SimpleConfig;
import com.mperon.util.java.ReflectException;
import com.mperon.util.java.ReflectUtils;

/**
 * The Class ConfigDAOCreator.
 * 
 * @author Marcos Peron
 */
public class ConfigDAOCreator extends SimpleDAOCreator {

    /** The config. */
    SimpleConfig config;

    /**
     * The Constructor.
     * 
     * @param cfg
     *            the cfg
     */
    public ConfigDAOCreator(SimpleConfig cfg) {
        super(cfg.get("daocreator.prefix"), cfg.get("daocreator.suffix"), cfg
                .get("daocreator.package"));
        config = cfg;
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.marcosperon.dao.DAOCreator#getDAO(java.lang.Class)
     */
    @Override
    public DAO<?> getDAO(Class<?> clz) {
        String className = buildDAOClassName(clz);

        // tenta encontrar um construtor que receba um arquivo simpleconfig ou tenta injetalo via
        // setter
        Object dao;
        try {
            Class<?> daoClass = ReflectUtils.fromName(className);

            if (ReflectUtils.findConstructor(daoClass, new Class<?>[] { clz.getClass(),
                    SimpleConfig.class }) != null) {

            } else if (ReflectUtils.findConstructor(daoClass, new Class<?>[] { clz.getClass() }) != null) {
                // tenta por dependency injection
            } else {
                // tenta tambem dependency injection
            }

            dao = ReflectUtils.newInstance(className, new Class[] { clz.getClass(),
                    SimpleConfig.class }, new Object[] { config });
        } catch (ReflectException e) {
            throw new DAOException("Was not possible to instantiate the dao", e);
        }
        if (dao instanceof DAO<?>) {
            return (DAO<?>)dao;
        } else {
            throw new DAOException("Was not possible to instantiate the dao");
        }
    }
}
